package com.baidu.erp.sercvice.impl;

import com.baidu.erp.dao.RoleDao;
import com.baidu.erp.domain.Role;
import com.baidu.erp.sercvice.RoleService;
import com.baidu.erp.utils.DateUtil;
import com.baidu.erp.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;
import java.util.Optional;

public class RoleServiceImpl implements RoleService {

    @Override
    public int save(Role role) {
        SqlSession sqlSession = null;
        try{
            sqlSession = MybatisUtil.getsqlSession();
            RoleDao roleDao = sqlSession.getMapper(RoleDao.class);
            role.setCreateTime(DateUtil.getCurrentTime());
            int count = roleDao.save(role);
            sqlSession.commit();
            return count;
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Optional<Role> getRoleByName(String name) {
        SqlSession sqlSession = MybatisUtil.getsqlSession();
        RoleDao roleDao = sqlSession.getMapper(RoleDao.class);
        Optional<Role> optionalRole = roleDao.getRoleByName(name);
        return optionalRole;
    }

    @Override
    public List<Role> getByPage(Integer pageNo, Integer pageSize) {
        SqlSession sqlSession = MybatisUtil.getsqlSession();
        RoleDao roleDao = sqlSession.getMapper(RoleDao.class);
        int startIndex = (pageNo - 1) * pageSize;
        return roleDao.getByPage(startIndex, pageSize);

    }

    @Override
    public Role getById(String id) {
        SqlSession sqlSession = MybatisUtil.getsqlSession();
        RoleDao roleDao = sqlSession.getMapper(RoleDao.class);
        return roleDao.getById(id);
    }

    @Override
    public int del(String[] idArr) {
        SqlSession sqlSession = null;
        try{
            sqlSession = MybatisUtil.getsqlSession();
            RoleDao roleDao = sqlSession.getMapper(RoleDao.class);
            int count = roleDao.del(idArr);
            sqlSession.commit();
            return count;
        }catch (Exception e){
            sqlSession.rollback();
            e.printStackTrace();
            return 0;
        }

    }
}
